﻿using System;
using System.Threading.Tasks;
using T.ServiceFramework.Service;
using T.ServiceFramework.Spi;
using T.ServiceComponent.Kernel.Service;

namespace T.SF.Console
{
    /// <summary>
    /// HSFHost关闭处理器
    /// </summary>
    class ShutdownHandler
    {
        /// <summary>
        /// 优雅地关闭HSFHost
        /// </summary>
        public static void GracefulShutdown(string showdownReason)
        {
            if (SFContext.Host == null)
            {
                return;
            }

            //try
            //{
            //    HostService.Current.HostClosed(SFContext.Host.ID);
            //}
            //catch (Exception ex) 
            //{
            //    Program.WriteRestartLog($"Host close throw exception: {ex}");
            //}

            if (RuntimeHookService.GetInstance().GetActionCount() > 0)
            {
                Parallel.ForEach(RuntimeHookService.GetInstance().GetActions(), (action) =>
                {
                    if (action.Value != null)
                    {
                        try
                        {
                            action.Value(new HookArgs { EventTime = DateTime.Now, EventType = HookEventType.AutoShutdown, Reason = showdownReason });
                        }
                        catch (Exception ex)
                        {
                            Program.WriteRestartLog(string.Format("Shutdown Event Extension: {0}, Failed: {1}", action.Key, ex.ToString()));
                        }
                    }
                });
            }
        }
    }
}
